//
//  QQTagView.m
//  QQtagView
//
//  Created by ZhangQun on 2017/4/8.
//  Copyright © 2017年 ZhangQun. All rights reserved.
//

#import "QQTagView.h"
#import "CustomBtn.h"

@interface QQTagView()<UITextFieldDelegate>
@property (nonatomic, strong) UITextField *searchTextF;
@end

@implementation QQTagView

- (instancetype)init
{
    if (self = [super init]) {
        self.tagFontSize = 12;
        self.tagSpace = 10;
        self.padding = UIEdgeInsetsMake(10, 10, 10, 10);//控件的距离
        self.Style = QQTagStyleNone;
        self.backgroundColor =[UIColor redColor];
        
    }
    return self;
}
- (instancetype)initWith:(QQTagStyle)TagViewStyle
{
    self = [super init];
    self.tagFontSize = 12;
    self.tagSpace = 10;
    self.Style = TagViewStyle;
    self.padding = UIEdgeInsetsMake(10, 10, 10, 10);//控件的距离
    self.backgroundColor =[UIColor redColor];
    [self addSubview:self.searchTextF];
    return self;
}
- (void)QQTagItem:(QQTagItem *)QQTagItem
{
    if([self.delegate respondsToSelector:@selector(QQTagView:QQTagItem:)]) {
        [self.delegate QQTagView:self QQTagItem:QQTagItem];
    }
    
    if (QQTagItem.Style == QQTagStyleEditNone) {
        [QQTagItem removeFromSuperview];
    }
}
- (void)changeTagStatus:(QQTagStyle)TagStyle string:(NSString *)string
{
    for (QQTagItem *item in self.subviews) {
        if([self stringIsEquals:item.text to:string]) {
            [item changeItemType:TagStyle];
        }
    }
}

-(BOOL)isExistWithLabel:(NSString *)text{
    BOOL isExist = NO;
    for (QQTagItem *item in self.subviews) {
        if([item respondsToSelector:@selector(text)] && [self stringIsEquals:item.text to:text]) {
            isExist = YES;
        }
    }
    return isExist;
}

- (void)remove:(NSString *)text
{
    for (QQTagItem *item in self.subviews) {
        if([self stringIsEquals:item.text to:text]) {
            [item removeFromSuperview];
        }
    }
    if (self.subviews.count == 1) {
        self.searchTextF.placeholder = NSLocalizedString(@"typeHereToSearch", nil);
    }
}

-(void)removeAllLabel{
    self.searchTextF.placeholder = @"";
    [self removeAllSubviews];
}

- (void)addTags:(NSArray *)tags
{
    for (int i = 0; i< tags.count; i++) {
        [self addLabel:tags[i] tag:i];
    }
}
- (void)addLabel:(NSString *)text tag:(NSInteger)tag {
    
    if ([self.searchTextF superview]) {
        self.searchTextF.placeholder = @"";
        [self.searchTextF removeFromSuperview];
    }
    
    CGRect frame = CGRectZero;
    if(self.subviews && self.subviews.count > 0) {
        frame = [self.subviews lastObject].frame;
    }
    
    QQTagItem *Item = [[QQTagItem alloc]init];
#warning mark - 是否显示删除图片 
    // 这里是RightView实现的也可以用CleanButtonMode实现
    /**
     UIButton *button = [label.label valueForKey:@"_clearButton"];
     [button setImage:[UIImage imageNamed:@"clear_icon"] forState:UIControlStateNormal];
     Item.clearButtonMode = UITextFieldViewModeAlways;
     */
    if (self.Style == QQTagStyleEditSlect) {
        UIView *rightVeiw = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 26, 26)];
        CustomBtn *button = [CustomBtn buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(4, 5, 16, 16);
        [button setImage:[UIImage imageNamed:@"btn_close"]
                forState:UIControlStateNormal];
        button.info = Item;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [rightVeiw addSubview:button];
        Item.rightView = rightVeiw;
        Item.rightViewMode = UITextFieldViewModeAlways;
        Item.padding = UIEdgeInsetsMake(6, 10, 6, 26);//字体与控件的距离
        Item.Style = QQTagStyleEditNone;
        Item.EditShowColor = RGBColor(153, 153, 153);
    }else{
        Item.padding = UIEdgeInsetsMake(10, 10, 10, 10);//字体与控件的距离
    }
    Item.text = text;
    Item.tag = tag;
    Item.mydelagete = self;
    Item.frame = CGRectMake(frame.origin.x, frame.origin.y, Item.frame.size.width, Item.frame.size.height);
    [Item sizeToFit];
    Item.layer.cornerRadius = 15;
    [self addSubview:Item];
    
    if (![self.searchTextF superview]) {
        self.searchTextF.frame = CGRectMake(0, 0, 30, 30);
        [self addSubview:self.searchTextF];
    }

}
- (void)buttonClick:(CustomBtn *)btn
{
    [self QQTagItem:btn.info];
}
- (void)layoutSubviews {
    [UIView beginAnimations:nil context:nil];
    CGFloat paddingRight = self.padding.right;
    CGFloat cellspace = 5;
    CGFloat y = self.padding.top;
    CGFloat x = self.padding.left;
    CGRect frame;
    for(UIView *tag in self.subviews) {
        frame = tag.frame;
        frame.origin.x = x;
        frame.origin.y = y;
        
        if(frame.origin.x + frame.size.width + paddingRight > self.frame.size.width) {
            // 换行
            frame.origin.x = self.padding.left;
            frame.origin.y = frame.origin.y + frame.size.height + cellspace;
            
            y = frame.origin.y;
        }
        
        if(frame.origin.x + frame.size.width > self.frame.size.width - paddingRight) {
            frame.size.width = self.frame.size.width - paddingRight - frame.origin.x;
        }
        
        x = frame.origin.x + frame.size.width + cellspace;
        tag.frame = frame;
    }
    
    CGFloat containerHeight = frame.origin.y + frame.size.height + self.padding.bottom;
    CGRect containerFrame = self.frame;
    containerFrame.size.height = containerHeight;
    self.frame = containerFrame;
    self.searchTextF.frame = CGRectMake(frame.origin.x, frame.origin.y, KSCREEN_WIDTH-frame.origin.x, 30);
    
    [UIView commitAnimations];
}

- (BOOL)stringIsEquals:(NSString *)string to:(NSString *)string2 {
    return [string isEqualToString:string2];
}

#pragma mark - textViewDelegate

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    //判断输入的字是否是回车，即按下return
    if([string isEqualToString:@"\n"]){
        //在这里做你响应return键的代码
        //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
        [textField endEditing:YES];
        return NO;
    }
            
        
    NSString *searchText;
    if (string.length) {
        if (range.length == 0) {
            searchText = [NSString stringWithFormat:@"%@%@",textField.text,string];
        }
        else{
            searchText = textField.text;
        }
    }
    else{
        searchText = [textField.text substringToIndex:range.location];
    }
    searchText = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSLog(@"searchtext:%@",searchText);
    if([self.delegate respondsToSelector:@selector(QQTagView:searchText:)]) {
        [self.delegate QQTagView:self searchText:searchText];
    }
    return YES;
}


-(UITextField *)searchTextF{
    if (!_searchTextF) {
        _searchTextF = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        _searchTextF.placeholder = NSLocalizedString(@"typeHereToSearch", nil);
        _searchTextF.delegate = self;
        _searchTextF.returnKeyType = UIReturnKeyDone;
    }
    return _searchTextF;
}

@end
